define(function () {
    // userInfo:  common.getTopWindowDom().userInfo; 登录用户信息
    if (window && window.dhx4) window.dhx4.skin = "material";
    if (window && window.dhtmlXCalendarObject) {
        dhtmlXCalendarObject.prototype.lang = "zh";
        dhtmlXCalendarObject.prototype.langData = {
            "zh": {
                dateformat: "%Y-%m-%d",
                hdrformat: "%Y年%F月",
                monthesFNames: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
                monthesSNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
                daysFNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
                daysSNames: ["日", "一", "二", "三", "四", "五", "六"],
                weekstart: 1,
                weekname: "w",
                today: "今天",
                clear: "清空"
            }
        };
    }
    $.fn.form2json = function () {
        var obj = {};
        $.each(this.serializeArray(), function (i, o) {
            var n = o.name, v = $.trim(o.value);
            obj[n] = obj[n] === undefined ? v
                : $.isArray(obj[n]) ? obj[n].concat(v)
                    : [obj[n], v];

        });
        return obj;
    };
    $.fn.json2form = function (data, isInitSwitchBtn, switchBtnParams, inputDialogSelect) {
        var _this = this;
        if (data) {
            $.each(data, function (i, o) {
                var jqObj = $(_this).find("[name='" + i + "']");
                var type = jqObj.attr("type");
                switch (type) {
                    case "text":
                        var dataType = jqObj.attr("data-type");
                        switch (dataType) {
                            case "date":
                                if (o) {
                                    var format = jqObj.attr("data-format") || '%Y-%m-%d';
                                    o = window.dhx4.template.date(o, format);
                                }
                                break;
                        }
                        jqObj.val(o);
                        break;
                    default:
                        jqObj.val(o);
                        break;
                }
                if (type == "checkbox" && isInitSwitchBtn) {
                    if (data[i] == switchBtnParams[i]["onValue"]) {
                        jqObj.prop("checked", "checked");
                    } else {
                        jqObj.removeAttr("checked")
                    }
                    jqObj.trigger("afterBindData");//注册绑定值后事件
                }
                if (inputDialogSelect && type == "text" && jqObj.parent().hasClass("hci-dialog-select")) {
                    var jqContent = jqObj.closest(".hci-dialog-select").find(".content");
                    var textName = jqContent.attr("name");
                    jqContent.text(data[textName]).attr({title: data[textName]});
                }
            });
        }
    };
    $.fn.toPy = function (param) {
        $(param["target"]).on("keyup", function () {

        })
        // $(this).on("keyup", function () {
        //     alert(1);
        // })
    };
    $.cookie = function (name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            var path = options.path ? '; path=' + options.path : '';
            var domain = options.domain ? '; domain=' + options.domain : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else {
            // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
    /**
     * 往后推几天
     * @param days
     * @constructor
     */
    Date.prototype.AddDay = function (days) {
        days = parseInt(days);
        return this.setDate(this.getDate() + days);
    };
    /**
     * 往后推几个月
     * @param months
     * @constructor
     */
    Date.prototype.AddMonth = function (months) {
        months = parseInt(months);
        return this.setMonth(this.getMonth() + months);
    };
    /**
     * 往后推几年
     * @param years
     * @constructor
     */
    Date.prototype.AddYear = function (years) {
        years = parseInt(years);
        return this.setFullYear(this.getFullYear() + years);
    };
    // Date.prototype.AddMinute = function (minutes) {
    //     // date.setMinutes(min + 5);
    //     ret
    // }

    var common = {
        getTopWindowDom: function () {
            var obj = window.self;
            var outTimes = 0;
            var upWindow = null;//上一个父级frame
            while (true) {
                //如果取不到，会一直卡下去--默认10次
                try {
                    if (obj.document.getElementById("flag_top_window_ky")) {
                        return obj;
                    }
                } catch (ex) {
                    return upWindow;
                }
                upWindow = obj.window;
                obj = obj.window.parent;
                if (outTimes > 10) {
                    return obj;
                }
                outTimes++;
            }
        },
        getParamFromUrl: function (key) {
            key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + key + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.href);
            if (results == null) {
                return null;
            } else {
                return decodeURIComponent(results[1]);
            }
        },
        getParamFromUrl2Json: function (url) {
            var url = url || window.location.href;
            var reg_url = /^[^\?]+\?([\w\W]+)$/,
                reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
                arr_url = reg_url.exec(url),
                ret = {};
            if (arr_url && arr_url[1]) {
                var str_para = arr_url[1], result;
                while ((result = reg_para.exec(str_para)) != null) {
                    ret[result[1]] = decodeURIComponent(result[2]);
                }
            }
            return ret;
        },
        /**
         * 获取当前字符串宽度
         * @param text
         * @param font
         * @returns {*}
         */
        getCurrentStrWidth: function (text, font) {
            var currentObj = $('<pre>').hide().appendTo(document.body);
            $(currentObj).html(text).css({font: font});
            var width = currentObj.width();
            currentObj.remove();
            return width;
        },
        reckonDate: function (type, num, format) {
            var dataValue = new Date();
            switch (type) {
                case "d":
                    dataValue = dataValue.AddDay(num);
                    break;
                case "m":
                    dataValue = dataValue.AddMonth(num);
                    break;
                case "y":
                    dataValue = dataValue.AddYear(num);
                    break;
            }
            dataValue = window.dhx4.template.date(dataValue, format);
            return dataValue;
        },
        isNumber: function (val) {
            return /^[(-?\d+\.\d+)|(-?\d+)|(-?\.\d+)]+$/.test(val + '');
        },
        /**
         *  界面上的日期插件初始化
         *  <input type='text' data-type='date' date-default-value='' >
         *  data-type:date  （必须有说明这个日期）
         *  data-default-value-type:d & m & y  （值推算类型--默认为d; d 代表 天；m 代表月； y 代表 年）
         *  data-default-value: 0 & n & -n     （默认日期:0代表 当前; n 代表 当前往后推 n 天/月/年 ;-n 代表 往后推 n 天/月/年）
         *  data-format:%Y-%m-%d (更多 格式详见 readme.md 中Date Format 说明）
         *  data-compare-value-type:d & m & y (同 date-default-value-type；配合 data-max-value 和 data-min-value 来推算）
         *  data-max-value: 0 & n & -n & id  (同 data-default-value)(id 其他时间输入框的控件的id 所获取的值)
         *  data-min-value:0 & n & -n  & id （同 data-min-value)
         */
        initCalendar: function (jqForm) {

            var self = this;
            var calendarArray = [];
            var jqCalendar;
            if (jqForm) {
                jqCalendar = $(jqForm).find('[data-type="date"]').attr({"autocomplete": "off"});
            } else {
                jqCalendar = $('[data-type="date"]').attr({"autocomplete": "off"});
            }

            $.each(jqCalendar, function (index, item) {
                var option = {
                    format: $(this).attr("data-format") || '%Y-%m-%d',
                    defaultValueType: $(this).attr("data-default-value-type") || 'd',
                    defaultValue: $(this).attr("data-default-value") || null,
                    compareValueType: $(this).attr("data-compare-value-type") || "d",
                    maxValue: $(this).attr("data-max-value") || null,
                    minValue: $(this).attr("data-min-value") || null
                }
                //日期 控件 初始化
                var calendar = new dhtmlXCalendarObject(item);
                //设置是否显示时间
                var format = option.format;
                if (!(format.indexOf("%h") > -1 || format.indexOf("%H") > -1 || format.indexOf("%g") > -1 || format.indexOf("%G") > -1)) {
                    calendar.hideTime();
                }
                //赋值操作
                calendar.setDateFormat(option.format);
                if (option.defaultValue != null) {
                    var dataValue = self.reckonDate(option.defaultValueType, option.defaultValue, option.format);
                    $(item).val(dataValue);
                }
                //设置取值范围
                item.onclick = function () {

                    var maxValue = null;
                    var minValue = null;
                    if (self.isNumber(option.minValue)) {
                        minValue = self.reckonDate(option.compareValueType, option.minValue, option.format);
                    } else {
                        minValue = $("#" + option.minValue).val() || null;
                    }
                    if (self.isNumber(option.maxValue)) {
                        maxValue = self.reckonDate(option.compareValueType, option.maxValue, option.format);
                    } else {
                        maxValue = $("#" + option.maxValue).val() || null;
                    }
                    try {
                        calendar.setSensitiveRange(minValue, maxValue);
                    } catch (ex) {
                        /* console.log(ex);*/
                    }
                }
                //判断取值范围
                calendarArray.push(calendar);
            });
            return calendarArray;
        },
        /**
         * 初始化 switchBtn
         * @param params
         */
        initSwitchBtn: function (params) {
            var jqSwitchBtn = $('input[type="checkbox"].btn-switch').hide();
            $.each(jqSwitchBtn, function () {
                var _this = this;
                var jqSwitchBtnOuter = $('<a class="btn-switch-outer"></a>')
                $(_this).wrap(jqSwitchBtnOuter);
                jqSwitchBtnOuter = $(this).closest(".btn-switch-outer");
                var isCheck = $(_this).prop('checked');
                var switchStatus = isCheck ? "on" : "off";
                jqSwitchBtnOuter.append('<span class="btn-switch btn-switch-' + switchStatus + '"><b class="btn-switch-inner"></b></span>');
                jqSwitchBtnOuter.on("click", function () {
                    var name = $(_this).attr("name");
                    var isContinue = true;
                    if (params[name] && typeof (params[name].beforeChange) == "function") {
                        isContinue = params[name].beforeChange()
                    }
                    if (isContinue) {
                        if (jqSwitchBtnOuter.find(".btn-switch-off").length > 0) {
                            jqSwitchBtnOuter.find(".btn-switch-off").removeClass("btn-switch-off").addClass("btn-switch-on");
                            $(_this).prop("checked", "checked");
                        } else {
                            jqSwitchBtnOuter.find(".btn-switch-on").removeClass("btn-switch-on").addClass("btn-switch-off");
                            $(_this).removeAttr("checked")
                        }
                        if (params[name] && typeof (params[name].afterChange) == "function") {
                            var isCheck = $(_this).prop('checked');
                            var value = isCheck ? params[name]["onValue"] : params[name]["offValue"];
                            params[name].afterChange(value);
                        }
                    }
                });
                $(_this).on("afterBindData", function () {
                    var _this = this;
                    var name = $(_this).attr("name");
                    var isCheck = $(this).prop("checked");
                    var switchStatus = isCheck ? "on" : "off";
                    var oldSwitchStatus = !isCheck ? "on" : "off";
                    $(this).closest(".btn-switch-outer").find(".btn-switch").removeClass("btn-switch-" + oldSwitchStatus).addClass("btn-switch-" + switchStatus);
                    if (params[name] && typeof (params[name].afterBindData) == "function") {
                        var value = isCheck ? params[name]["onValue"] : params[name]["offValue"];
                        params[name].afterBindData(value);
                    }
                });
            })
        },
        /**
         * 表单验证
         * @param jqForm
         * @param ignoreHidden
         */
        initValidForm: function (jqForm, ignoreHidden) {
            $.extend($.Datatype, {
                "intNum": /^0|([+-]?([1-9]\d*))$/,
                // 正整数
                "intNumN": /^[+]{0,1}(\d+)$/,
                //日期时间： YYYY-MM-DD HH:MM
                "datetime": /^(\d{4}\-(11|12|0[1-9])\-(30|31|[0-2]\d) (20|21|22|23|[0-1]\d)\:[0-5]\d)$/,
                //日期： YYYY-MM-DD
                "y-m-d": /^(\d{4}\-(10|11|12|0[1-9])\-(30|31|[0-2]\d))$/,
                // 日期验证，可以验证闰年等
                //^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$
                // 月日 MM-DD
                "m-d": /^((10|11|12|0[1-9])\-(30|31|[0-2]\d))$/,
                // 时间：HH:MM
                "time": /^((20|21|22|23|[0-1]\d)\:[0-5]\d)$/,
                // name: 50字
                "name": /^.{1,50}$/,
                // code： 数字 字母 下划线
                "code": /^[0-9a-zA-Z_\-]{1,}$/,
                // 手机号码验证格式使用 m
                // 如果需要同时验证手机或座机 使用 m|phone
                // 座机号码
                "phone": /^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$/,
                // 与默认的验证 m 重复
                //"tel": /^\d{3}$|^\d{11}$|^\d{7,8}$|^(\d{4}|\d{3})-(\d{7,8})$|^(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})$|^(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})$/,
                // 允许为空验证，搭配其它验证使用 另应放在前如 null|phone
                "null": /^\s*$/
            });
            $.extend($.Tipmsg, {
                w: {
                    "datetime": "日期时间格式不正确，应为YYYY-MM-DD HH:mm",
                    "y-m-d": "年月日格式不正确，应为YYYY-MM-DD",
                    "m-d": "月日格式不正确，应为MM-DD",
                    "time": "时间格式不正确!",
                    "name": "该字段最多只能输入50个字",
                    "code": "只能输入数字,字母或下划线",
                    "phone": "无效的电话号码",
                    "intNum": "请填整数",
                    "intNumN": "请输入正整数"
                    //"tel": "无效的电话号码！"
                }
            });
            var validFormObj = $(jqForm).Validform({
                ignoreHidden: ignoreHidden,
                tiptype: function (msg, o, cssctl) {

                    if (!o.obj.is("form")) {
                        // var _input = o.obj;
                        // if ($(_input).attr("selId")) {
                        //     var selId = $(_input).attr("selId");
                        //     $("#" + selId).find(".dhxcombo_material").addClass("Validform_error");
                        // }

                        $(o.obj).focus(function () {
                            var _this = this;
                            if ($(_this).hasClass("Validform_error")) {
                                var frmOffset = window.dhx4.getOffset(jqForm[0]);
                                var offset = window.dhx4.getOffset(_this);
                                if (jqForm.find(".text-up-tips").length == 0) {
                                    var tipArray = [
                                        '<span class="text-up-tips tips-error" style="display:none;">',
                                        '<i class="text-up-tips-arrow arrow-red"></i>',
                                        '<span class="msg"></span>',
                                        '</span>'
                                    ];
                                    var tipHtml = tipArray.join('');
                                    jqForm.append(tipHtml);
                                }
                                $(".text-up-tips", jqForm).find(".msg").html(msg);
                                $(".text-up-tips", jqForm).css({
                                    "z-index": 99999,
                                    "top": offset.top - frmOffset.top - $(o.obj).outerHeight() - 2,
                                    "left": offset.left - frmOffset.left - 20
                                }).show();
                            }

                            if ($(_this).hasClass("Validform_error") && $(this).attr("selId")) {
                                var selId = $(_this).attr("selId");
                                $("#" + selId).find(".dhxcombo_material").addClass("Validform_error");
                            }


                        });
                        $(o.obj).blur(function () {
                            var _this = this;
                            $(".text-up-tips", jqForm).hide();
                            if ($(_this).hasClass("Validform_error") && $(_this).attr("selId")) {
                                var selId = $(_this).attr("selId");
                                $("#" + selId).find(".dhxcombo_material").addClass("Validform_error");
                            }
                        });
                    }
                }
            });
            return validFormObj;
        },
        /**
         * 初始化inputDialogSelect
         * @param params
         */
        initDialogSelect: function (params) {
            $.each(params, function (selIndex, selParam) {
                var jqDialogSelect;
                var type = selParam["type"] || "input";
                switch (type) {
                    case "input":
                        var jqInput = $('input[name="' + selIndex + '"]').hide();
                        var jqDialogSelectOuter = $("<span class='hci-dialog-select'></span>");
                        $(jqInput).wrap(jqDialogSelectOuter);
                        var jqContent = $("<span class='content' name='" + selParam["textName"] + "'></span>");
                        jqDialogSelect = jqInput.closest(".hci-dialog-select");
                        jqDialogSelect.append(jqContent);
                        break;
                    default:
                        if (typeof (selParam["target"]) == "function") {
                            jqDialogSelect = $(selParam['target']())
                        } else {
                            jqDialogSelect = $(selParam['target']);
                        }
                        break;
                }
                jqDialogSelect.on("click", function () {
                    var enable = true
                    if (typeof (selParam["enableEvent"]) == "function") {
                        enable = selParam["enableEvent"]();
                    }
                    if (!enable) {
                        return;
                    }
                    var __this = this;
                    var top = common.getTopWindowDom();
                    var urlParam = {}, urlParamArray = [], urlParamStr = "";
                    if (typeof (selParam["urlParam"]) == "function") {
                        urlParam = selParam["urlParam"]();
                    }
                    $.each(urlParam, function (key, value) {
                        urlParamArray.push(key + "=" + value);
                    });
                    urlParamStr = urlParamArray.join("&");
                    require([GLOBAL_WEB_BASE_PATH + '/script/select/part/' + urlParam["partName"] + '.js'], function (internal) {
                        var dialogSelectInputParam = internal.dialogSelectInputParam(urlParam);
                        var param = $.extend(true, {}, dialogSelectInputParam);
                        top[param["winStorage"]] = [];
                        if (type == "input") {
                            var text = $(__this).find(".content").text(), value = $(__this).find("input").val();
                            var dataInfo = {};
                            if (text && value) {
                                dataInfo[param["textField"]] = text;
                                dataInfo[param["valueField"]] = value;
                                top[param["winStorage"]].push(dataInfo);
                            }

                        } else {
                            if (selParam["data"] && typeof (selParam["data"]) == "function") {
                                var data = selParam.data();
                                top[param["winStorage"]] = data;
                            } else {
                                top[param["winStorage"]] = [];
                            }
                        }

                        var btnOk = function (dialogIndex) {
                            top[param["winCallback"]](dialogIndex, function (data) {
                                if (data.length > 0) {
                                    top.layer.close(dialogIndex);
                                    if (type == "input") {
                                        $(__this).find("input").val(data[0][param["valueField"]]);
                                        $(__this).find(".content").text(data[0][param["textField"]]).attr({title: data[0][param["textField"]]});
                                    } else {
                                        selParam["callback"](data);
                                    }
                                }
                                // 值改变事件
                                selParam['onChange'] && typeof (selParam["onChange"]) == "function" && selParam['onChange'](data[0][param["valueField"]], data[0][param["textField"]]);
                            });
                        };
                        var btnCancel = function (dialogIndex) {
                            common.getTopWindowDom().layer.close(dialogIndex)
                        };
                        var dialogParam = {
                            title: param["title"],
                            area: [param["width"], param["height"]],
                            content: window.GLOBAL_WEB_BASE_PATH + "/select/list.html?" + urlParamStr,
                            btn: param["btn"] || ['保存', '取消']
                        }
                        if (param['btn']) {
                            $.each(param['btn'], function (btnIndex, btnText) {
                                var btnIndex = "btn" + btnIndex;
                                var btnEvent = param[btnIndex];
                                if (btnEvent == "ok") {
                                    dialogParam[btnIndex] = btnOk;
                                } else if (btnEvent == "cancel") {
                                    dialogParam[btnIndex] = btnCancel;
                                } else {
                                    dialogParam[btnIndex] = function (dialogIndex) {
                                        var fnCallback = function (data) {
                                            if (type == "input") {
                                                $(__this).find("input").val(data[0][param["valueField"]]);
                                                $(__this).find(".content").text(data[0][param["textField"]]).attr({title: data[0][param["textField"]]});
                                            } else {
                                                selParam["callback"](data);
                                            }
                                            // 值改变事件
                                            selParam['onChange'] && typeof (selParam["onChange"]) == "function" && selParam['onChange'](data[0][param["valueField"]], data[0][param["textField"]]);
                                        };
                                        btnEvent(dialogIndex, fnCallback);
                                    };
                                }
                            });
                        } else {
                            dialogParam["btn1"] = btnOk;
                            dialogParam["btn2"] = btnCancel;
                        }
                        common.dialog(dialogParam);
                    });
                });
            });
        },
        /**
         * 成功消息提醒
         * @param msg
         */
        successMsg: function (msg) {
            dhtmlx.message({
                type: "success",
                text: msg,
                expire: 1500//1.5s后自动消失
            });
            var width = common.getCurrentStrWidth(msg, "12px/1.5 Arial, Microsoft YaHei") + 80;
            width = width < 250 ? width : 250;
            var left = $("body").innerWidth() / 2 - $(".dhtmlx-success").closest(".dhtmlx_message_area").outerWidth() / 2;
            var top = $("body").innerHeight() > 500 ? 200 : 60;
            $(".dhtmlx-success").closest(".dhtmlx_message_area").css({
                "position": "fixed",
                "z-index": 9999,
                "left": left,
                "top": top,
                "width": width
            });
        },
        /**
         * 错误（失败）消息提醒
         * @param msg
         */
        errorMsg: function (msg) {
            dhtmlx.message({
                type: "error",
                text: msg,
                expire: 1500 //1.5s后自动消失
            });
            var width = common.getCurrentStrWidth(msg, "12px/1.5  Arial, Microsoft YaHei") + 80;
            width = width < 250 ? width : 250;
            var left = $("body").innerWidth() / 2 - $(".dhtmlx-error").closest(".dhtmlx_message_area").outerWidth() / 2;
            var top = $("body").innerHeight() > 500 ? 200 : 60;
            $(".dhtmlx-error").closest(".dhtmlx_message_area").css({
                "position": "fixed",
                "z-index": 9999,
                "top": top,
                "left": left,
                "width": width
            });
        },
        confirm: function (options) {
            var top = common.getTopWindowDom();
            top.focus();
            top.dhtmlx.confirm({
                ok: "是",
                cancel: '否',
                text: options["text"],
                callback: function (result) {
                    if (typeof (options["callback"]) == "function") {
                        options["callback"](result);
                    }
                }
            });
        },
        dialog: function (param) {
            var defParams = {
                title: '',
                type: 2, //此处以iframe举例
                area: ['620px', '350px'],
                shade: 0.5,
                maxmin: false,
                content: GLOBAL_WEB_BASE_PATH + '/' + "jdbc/database/detail.html"
            };
            if (!param["btn"]) {
                defParams["btn"] = ['保存', '关闭'];
                defParams["btn1"] = function (dialogIndex) {
                    top["win_callback"](dialogIndex, function () {

                    })
                };
                defParams["btn2"] = function (dialogIndex) {
                    common.getTopWindowDom().layer.close(dialogIndex)
                }
            }
            param = $.extend(true, {}, defParams, param);
            return common.getTopWindowDom().layer.open(param);
        },
        //伪guid
        guid: function () {
            var guid = Guid.NewGuid();
            return guid.ToString("D");
        },
        makeDownload: function (url) {
            var iframe = $("#downFrame");
            if (!iframe || iframe.length == 0) {
                iframe = $("<iframe id='downFrame' name='downFrame' style='display:none;'></iframe>").appendTo($("body"));
            }
            iframe.attr({src: url});
        },
        //将ID、ParentID这种数据格式转换为树格式
        arrayToTree: function (data, id, pid) {
            if (!data || !data.length) return [];
            var targetData = [];                    //存储数据的容器(返回)
            var records = {};
            var itemLength = data.length;           //数据集合的个数
            for (var i = 0; i < itemLength; i++) {
                var o = data[i];
                records[o[id]] = o;
            }
            for (var i = 0; i < itemLength; i++) {
                var currentData = data[i];
                var parentData = records[currentData[pid]];
                if (!parentData) {
                    targetData.push(currentData);
                    continue;
                }
                parentData.children = parentData.children || [];
                parentData.children.push(currentData);
            }
            return targetData;
        },
        template: function (str, dataObj) {
            str = str.replace(/#\{(\w+)\}/g, function (m, i) {
                if (dataObj[i] != undefined) {
                    return dataObj[i];
                } else {
                    return m;
                }
            });
            return str;
        },
        getSysParam: function (paramKey, callback) {
            require(["request"], function (Request) {
                var req = new Request('api/sys/param');
                req.get({
                    data: {
                        paramKey: paramKey
                    },
                    success: function (data) {
                        callback && callback.call(this, data);
                    }
                });
            });
        },
        // 获取人员信息，默认在首页中赋值。
        getUserInfo: function () {
            var userInfo = common.getTopWindowDom().userInfo;
            if (!userInfo) {
                $.ajax({
                    url: GLOBAL_RESOURCE_PATH + 'api/current/user/info',
                    type: 'GET',
                    async: false,   //同步获取
                    success: function (data) {
                        userInfo = data;
                        common.getTopWindowDom().userInfo = userInfo;
                    }
                })
            }
            return common.getTopWindowDom().userInfo;
        }
    };

    return common;
});

